package com.zmn.oms.third.taobao;

import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import com.taobao.api.internal.tmc.TmcClient;
import com.taobao.api.internal.toplink.LinkException;
import com.zmn.oms.manager.utils.SpringBeanFactoryUtil;
import com.zmn.oms.third.taobao.msghandler.TmcMsgHandler;
import lombok.extern.slf4j.Slf4j;


/**
 * 类描述：淘宝无忧购消息接收器
 *
 * @author LiangHailong
 * @date 2019/06/05 17:12
 */
@Slf4j
public class TaobaoMessageAccepter {
    private TmcClient tmcClient;

    public TaobaoMessageAccepter() {
        initTmcClient();
    }

    /**
     * 创建淘宝队列监听器对象
     */
    private void initTmcClient() {
        TmcClient client = new TmcClient(TaobaoTmcConstants.APPKEY, TaobaoTmcConstants.SECRET);
        client.setMessageHandler(new MessageHandler() {
            @Override
            public void onMessage(Message message, MessageStatus status) {
                String topic = message.getTopic();
                TmcMsgHandler tmcMsgHandler = null;
                String tag = null;

                // 订单消息
                if (TaobaoTmcConstants.TOPIC_FUWU_WORKCARD_INFO.equals(topic)) {
                    tag = "订单";
                    tmcMsgHandler = SpringBeanFactoryUtil.getBean("orderTmcMsgHandler");
                }
                // 投诉消息
                else if (TaobaoTmcConstants.TOPIC_FUWU_ANOMALY_RECOURSE.equals(topic)) {
                    tag = "投诉";
                    tmcMsgHandler = SpringBeanFactoryUtil.getBean("complaintTmcMsgHandler");
                }
                // 服务预警单消息
                else if (TaobaoTmcConstants.TOPIC_FUWU_SERVICE_MONITOR.equals(topic)) {
                    tag = "预警";
                    tmcMsgHandler = SpringBeanFactoryUtil.getBean("orderWarnTmcMsgHandler");
                }
                // 订单其他操作节点消息
                else if (TaobaoTmcConstants.TMALL_FUWU_WORKCARD_STATUS_UPDATE.equals(topic)) {
                    tag = "订单其他操作";
                    tmcMsgHandler = SpringBeanFactoryUtil.getBean("orderOtherTmcMsgHandler");
                }
                // 其他
                else {
                    tag = "未知";
                    tmcMsgHandler = SpringBeanFactoryUtil.getBean("defaultTmcMsgHandler");
                }

                log.info("【{}】收到{}消息 Topic:[{}], Content:[{}]",
                        TaobaoTmcConstants.NAME_TMALL, tag, topic, message.getContent());

                tmcMsgHandler.procMsg(message, status);
            }
        });

        tmcClient = client;
    }

    /**
     * 连接淘宝消息队列，启动消息监听
     */
    public void connect() {
        try {
            tmcClient.connect(TaobaoTmcConstants.MESSAGE_QUEUE_URL);
        } catch (LinkException e) {
            log.error(e.getMessage(), e);
        }
    }

}
